import socket

# 创建一个TCP/IP套接字
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)


# 绑定服务器地址和端口
server_socket.bind(('127.0.0.1', 12345))

# 监听来自客户端的连接
server_socket.listen(5)
print(f"等待客户端连接...")



def rev_data(client_socket):  # 接收信息
    rev = client_socket.recv(1024).decode()
    print(f"收到消息: {rev}")
    try:
        oper, num1, num2 = rev.split(',')
        num1 = int(num1)
        num2 = int(num2)
        # 执行加法或减法操作
        if oper == "+":
            result = num1 + num2
        elif oper == "-":
            result = num1 - num2
        else:
            result = "无效操作"
        # 发送结果给客户端
        client_socket.send(str(result).encode())
    except Exception as e:
        client_socket.send("操作失败".encode())
        print(f"操作失败: {e}")

    client_socket.close()


while True:
    client_socket, addr = server_socket.accept()
    print(f"接受来自 {addr[0]}:{addr[1]} 的连接")

    # 处理客户端请求
    rev_data(client_socket)